<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require $_SERVER['DOCUMENT_ROOT'].'/nsbbs/conf/app.config.php';
require $_SERVER['DOCUMENT_ROOT'].'/nsbbs/PHPMailer/src/Exception.php';
require $_SERVER['DOCUMENT_ROOT'].'/nsbbs/PHPMailer/src/PHPMailer.php';
require $_SERVER['DOCUMENT_ROOT'].'/nsbbs/PHPMailer/src/SMTP.php';
Class Mail
{
	private $_mail;
	private static $_instance = null;
	private function __construct(){
		$this->_mail = new PHPMailer();
		$this->_mail->CharSet = CHARSET;
		$this->_mail->isSMTP();
		$this->_mail->Host = MAIL_HOST;
		$this->_mail->SMTPAuth = true;
		$this->_mail->Username = USERNAME;
		$this->_mail->Password = PASSWORD;
		$this->_mail->Port = MAIL_PORT;
		$this->_mail->SMTPSecure = 'ssl';
		$this->_mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer' => false,
				'allow_self_signed' => true
			)
		);
		$this->_mail->setFrom(USERNAME, FROM); 

		$this->_mail->isHTML();
	}
	//禁止克隆
	private function __clone(){}

	public static function getInstance (){
		if(!self::$_instance){
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	//log写入
	private function writelog($err){
		$err_time = date('Y-m-d H:i:s');
		$fd = fopen(LOG_PATH.'/err.log', 'a');
		fwrite($fd, "{$err}==时间：{$err_time}\n");
		fclose($fd);
	}

	public function send(array $options){
		if(count($options) != 4){
			exit('参数有四个(toemail,toname,subject,body)');
		}
		$this->_mail->addAddress($options['toemail'], $options['toname']); 
		$this->_mail->Subject = $options['subject'];
		$this->_mail->Body = $options['body'];
		$this->_mail->AltBody = '邮件客户端不支持HTML邮件';
		if($this->_mail->send()){
			return true;
		}else{
			$this->writelog('邮件发送错误:'.$this->_mail->ErrorInfo);
			return false;
		}
	}
}